//
//  StatusTableDelegate.m
//  weibo3
//
//  Created by Tian Wu on 11-4-13.
//  Copyright 2011年 nfsysu. All rights reserved.
//

#import "StatusTableDelegate.h"
#import "StatusCell.h"

#define LISTVIEW_CELL_IDENTIFIER		@"StatusCell"

@implementation StatusTableDelegate

- (void)awakeFromNib
{
	[listView setCellSpacing:0.0f];
	[listView setAllowsEmptySelection:YES];
    [listView setBackgroundColor:[NSColor grayColor]];
    
	
}

- (NSUInteger)numberOfRowsInListView: (PXListView*)aListView
{
#pragma unused(aListView)
	return [[_rootViewController publicData] count];
}

- (CGFloat)listView:(PXListView*)aListView heightOfRow:(NSUInteger)row
{
    if ([_tabtable selectedRow] == 3){
        WComment *statusForRow = [[_rootViewController publicData] objectAtIndex:row];
        NSString *staText = [NSString stringWithString:@""];
        if ([[statusForRow reply_comment] text] != NULL) {
            staText = [NSString stringWithFormat:@"%@\n----------------\n@%@:%@",[statusForRow text],[[[statusForRow reply_comment] user] name],[[statusForRow reply_comment] text]];
        }
        else{
            staText = [NSString stringWithFormat:@"%@\n----------------\n@%@:%@",[statusForRow text],[[[statusForRow status] user] name],[[statusForRow status] text]];
        }
        NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:staText] autorelease];
        NSTextContainer *textContainer = [[[NSTextContainer alloc]
                                           initWithContainerSize: NSMakeSize(NSWidth([listView contentViewRect]) - 113, FLT_MAX)] autorelease];
        NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
                                          autorelease];
        [layoutManager addTextContainer:textContainer];
        [textStorage addLayoutManager:layoutManager];
        [textStorage addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Lucida Grande" size:12.0]
                            range:NSMakeRange(0, [textStorage length])];
        [textContainer setLineFragmentPadding:5.0];
        (void) [layoutManager glyphRangeForTextContainer:textContainer];
        
        if([layoutManager
            usedRectForTextContainer:textContainer].size.height +37 < 66){
            return 66;
        }
        else{
            return ([layoutManager
                     usedRectForTextContainer:textContainer].size.height + 40);
        }

        
    }
    else{
        NSString *staText = [[[_rootViewController publicData] objectAtIndex:row] text];
        if ([[[_rootViewController publicData] objectAtIndex:row] retweeted_status] != NULL) {
            staText = [staText stringByAppendingFormat:@"\n----------------\n@%@:%@",[[[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] user] name],[[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] text]];
        }
        NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:staText] autorelease];
        NSTextContainer *textContainer = [[[NSTextContainer alloc]
                                           initWithContainerSize: NSMakeSize(NSWidth([listView contentViewRect]) - 103, FLT_MAX)] autorelease];
        NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
                                          autorelease];
        [layoutManager addTextContainer:textContainer];
        [textStorage addLayoutManager:layoutManager];
        [textStorage addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Lucida Grande" size:12.0]
                            range:NSMakeRange(0, [textStorage length])];
        [textContainer setLineFragmentPadding:5.0];
        (void) [layoutManager glyphRangeForTextContainer:textContainer];
        
        
        if([layoutManager
            usedRectForTextContainer:textContainer].size.height +37 < 60){
            
            if([[[_rootViewController publicData] objectAtIndex:row] thumbnail_pic] != nil ||
               [[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] thumbnail_pic] != nil){
                return 163;
            }
            else{
                return 66;
            }
            
        }
        else{
            
            if([[[_rootViewController publicData] objectAtIndex:row] thumbnail_pic] != nil ||
               [[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] thumbnail_pic] != nil){
                return ([layoutManager
                         usedRectForTextContainer:textContainer].size.height + 140);
            }
            else{
                return ([layoutManager
                         usedRectForTextContainer:textContainer].size.height + 40);
            }
        }
    }
    
}

- (PXListViewCell*)listView:(PXListView*)aListView cellForRow:(NSUInteger)row
{
	StatusCell *cell = (StatusCell *)[aListView dequeueCellWithReusableIdentifier:LISTVIEW_CELL_IDENTIFIER];
	dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
	if(!cell) {
		cell = [StatusCell cellLoadedFromNibNamed:@"StatusCell" reusableIdentifier:LISTVIEW_CELL_IDENTIFIER];
	}
    
    if ([_tabtable selectedRow] == 3){
        WComment *statusForRow = [[_rootViewController publicData] objectAtIndex:row];
        dispatch_async(concurrentQueue, ^{
            
            [[cell name] setStringValue:[[statusForRow user] name]];
            
            if ([[statusForRow reply_comment] text] != NULL) {
                [[cell text] setStringValue:[NSString stringWithFormat:@"%@\n----------------\n@%@:%@",[statusForRow text],[[[statusForRow reply_comment] user] name],[[statusForRow reply_comment] text]]];
            }
            else{
                [[cell text] setStringValue:[NSString stringWithFormat:@"%@\n----------------\n@%@:%@",[statusForRow text],[[[statusForRow status] user] name],[[statusForRow status] text]]];
            }
            
            NSString *temp = [[[statusForRow created_at] description] 
                              substringWithRange:NSMakeRange(4, 12)];
            [[cell time] setStringValue:temp];
            NSImage *image = [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[[statusForRow user] profile_image_url]]];
            dispatch_sync(mainQueue, ^{
                [[cell img] setImage:image];
            });
            [image release];
        }); 
    }
    else{
        
        Status *statusForRow = [[_rootViewController publicData] objectAtIndex:row];
        cell.thisStatus = statusForRow;
        
        
        
        
            [[cell name] setStringValue:[[statusForRow user] name]];
            if([statusForRow retweeted_status] != NULL){
                [[cell text] setStringValue:[NSString stringWithFormat:@"%@\n----------------\n@%@:%@",[statusForRow text],[[[statusForRow retweeted_status] user] name],[[statusForRow retweeted_status] text]]];
            }
            else{
                [[cell text] setStringValue:[statusForRow text]]; 
            }
            [[cell time] setStringValue:[[[statusForRow created_at] description] 
                                         substringWithRange:NSMakeRange(4, 12)]];
        dispatch_async(concurrentQueue, ^{
            NSImage *temp = [[[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[[statusForRow user] profile_image_url]]] autorelease];
            dispatch_sync(mainQueue, ^{
                if (cell.row == row) {
                    [[cell img] setImage:temp];
                }
            });
        });           
        
        if([[[_rootViewController publicData] objectAtIndex:row] thumbnail_pic] == nil ){
            
            if ([[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] thumbnail_pic] != nil) {
                
                
                dispatch_async(concurrentQueue, ^{
                    NSImage *temp = [[[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[[[[_rootViewController publicData] objectAtIndex:row] retweeted_status] thumbnail_pic]]] autorelease];
                    dispatch_sync(mainQueue, ^{
                        if (cell.row == row) {
                            [[cell pic] setImage:temp];
                        }
                        
                    });
                });                
            }
            else{
                /*
                dispatch_async(mainQueue, ^{
                    [[cell pic] setImage:[NSImage imageNamed:@"nilImage.png"]];
                });
                 */
            }
            
        }
        else{
            
            dispatch_async(concurrentQueue, ^{
                NSImage *temp = [[[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[[[_rootViewController publicData] objectAtIndex:row] thumbnail_pic]]] autorelease];
                dispatch_sync(mainQueue, ^{
                    if (cell.row == row) {
                        [[cell pic] setImage:temp];
                    }
                });
            }); 
                    
        }
    }
    
    
	return cell;
}


- (void)listViewSelectionDidChange:(NSNotification*)aNotification{
    if ([_tabtable selectedRow] == 3) {
        
        [_rootViewController replyCommentInRow:[listView selectedRow]];
        
    }
    else{
        [_rootViewController viewImageInRow:[listView selectedRow]];     
    }
   
    
}




- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

@end
